package com.ldr.custom.spring.v3.aop.utils;

import com.ldr.custom.spring.v3.aop.GPJdkDynamicAopProxy;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

public class GPAopProxyUtils {


    public static Object getTargetObject(Object proxy) throws NoSuchFieldException, IllegalAccessException {

        //先判断一下，这个传进来的这个对象是不是一个代理过的对象
        if (!isAopProxy(proxy)) {
            return proxy;
        }

        return getProxyTargetObject(proxy);
    }


    private static boolean isAopProxy(Object obj) {
        return Proxy.isProxyClass(obj.getClass());
    }

    private static Object getProxyTargetObject(Object proxy) throws NoSuchFieldException, IllegalAccessException {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        //强吻
        h.setAccessible(true);
        GPJdkDynamicAopProxy aopProxy = (GPJdkDynamicAopProxy) h.get(proxy);
        Field target = aopProxy.getClass().getDeclaredField("target");
        target.setAccessible(true);
        return target.get(aopProxy);
    }
}
